package com.qf.controller;

import com.qf.vo.UserVO;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class UploadController {

    @RequestMapping("/pic")
    public void download(String picfile, HttpServletResponse response) throws IOException {
        // 1. 找到存放头像文件的目录
        String path = "D:\\00qd-2304\\upload\\";
        // 2. 找到文件的全路径
        String finalFilepath = path + picfile;
        //3. 把头像文件响应给浏览器(把头像文件写入本次响应的响应体中)
        IOUtils.copy(new FileInputStream(finalFilepath),response.getOutputStream());

    }


    @PostMapping("/up")
    public HashMap<String,Object> upload(UserVO userVO) throws IOException {

//        MultipartFile file01 = files.get(0);
        MultipartFile file01 = userVO.getFile01();
        // 1. 要把浏览器上传的文件放到服务器上的哪个目录下？
        String path = "D:\\00qd-2304\\upload\\";

        // 2. 处理上传的文件在保存时使用的文件名
        String filename = UUID.randomUUID().toString();
        String originalFilename = file01.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extName = originalFilename.substring(index); // 原来上传的文件的扩展名

        // 3. 得到要存放的文件的最终的路径
        String finalFilePath = path + filename + extName;
        // 4. 保存文件
        file01.transferTo(new File(finalFilePath));

        HashMap<String, Object> result = new HashMap<>();
        result.put("code",1);
        result.put("msg","ok");
        result.put("data",filename + extName);

        return result;
    }



}
